import axios from 'axios'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:6060', // 网关地址
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 自动添加token
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一处理响应
service.interceptors.response.use(
  response => {
    const { code, message, data } = response.data
    const traceId = response.headers['x-trace-id'] || response.config.headers['X-Trace-Id']
    
    console.log('✅ 响应成功:', {
      url: response.config.url,
      status: response.status,
      traceId: traceId,
      data: response.data
    })
    
    if (code === 200) {
      return data // 直接返回data部分
    } else {
      console.error('业务错误:', message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    console.error('请求错误:', error.message)
    if (error.response?.status === 401) {
      // Token过期或无效，跳转到登录页
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 导出封装的请求方法
export const request = {
  get: (url, config) => service.get(url, config),
  post: (url, data, config) => service.post(url, data, config),
  put: (url, data, config) => service.put(url, data, config),
  delete: (url, config) => service.delete(url, config),
  patch: (url, data, config) => service.patch(url, data, config)
}

export default service
